package com.gt.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

@Slf4j
@Component
public class LogMdcFilter extends OncePerRequestFilter {
    public final static String TRACE_ID = "trace_id";
    public final static String TRACE_URI = "uri";
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return false;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String uri = request.getRequestURI();
//        uuid太长了，日志都要换行
//        String uuid =  UUID.randomUUID().toString().replace("-","");
//        uuid += PbUtils.getRandomString("0123456789", 5);
        log.info("LogMdcFilter请求地址:{}",uri);
        String uuid = "" + System.currentTimeMillis() + (1000 + new Random().nextInt(9000));
        MDC.put(TRACE_URI, uri);
        MDC.put(TRACE_ID, uuid);
        log.info("LogMdcFilter的mdc:{}",uuid);
        chain.doFilter(request, response);
        MDC.remove(TRACE_ID);
        MDC.remove(TRACE_URI);
        response.setHeader("Access-Control-Allow-Origin","*");
    }
}
